<?php

namespace app\api\controller\command;

use app\common\model\dealer\Order as OrderModel;
use app\common\model\dealer\User as UserModel;
use app\common\model\dealer\Referee as RefereeModel;
use think\Cache;

/**
 * 分销排行榜定时任务
 */
class Dealer
{
    //定时缓存分销榜单数据：           团队总推荐用户排行（显示前100名） 显示每个人伞下单数的总和
    public function saveDealerRankData($return = false)
    {
        set_time_limit(0);
        $teamRankData = [];
        $userData = UserModel::alias('du')
            ->join('user u', 'du.user_id = u.user_id')
            ->where("du.is_delete",0)
            ->field("du.user_id,u.nickName,u.avatarUrl")
            ->select();
        $imgArr = [];
        if(empty($userData)){
            return [];
        }
        foreach ($userData as $key => $value) {
            $userId = $value['user_id'];
            $totalIdsArr = $this->getTotalReferee([$userId]);
            $totalIdsArr = array_merge($totalIdsArr,[$userId]);
            $ownOrderNum = 0;
            if(!empty($totalIdsArr)){
                $totalIdsArr = array_merge($totalIdsArr,[$userId]);
                $ownOrderNum = OrderModel::alias("do")
                    ->join("order o","do.order_id=o.order_id","LEFT")
                    ->where("do.order_type",10)
                    ->where("do.first_user_id",'in',$totalIdsArr)
                    ->where("o.pay_status",20)
                    ->count('do.id');//总伞下有效单数
            }
            $imgArr[$userId] = ['nickName'=>$value['nickName'],'avatarUrl'=>$value['avatarUrl']];
            $teamRankData[$userId] = $ownOrderNum;
        }

        arsort($teamRankData);
        if(count($teamRankData)>100){
            $resRankData = array_slice($teamRankData,0,100,true);
        }else{
            $resRankData = $teamRankData;
        }

        $res = [];
        foreach ($resRankData as $key => $value) {
            if($value>0){
                $res[] = [
                    'counts' => $value,
                    'nickName' => $imgArr[$key]['nickName'],
                    'avatarUrl' => $imgArr[$key]['avatarUrl'],
                ];
            }
        }

        Cache::set("team_CacheDealRank", $res, 7200);// 如未刷新，缓存时间2小时

        if($return){
            return $res;
        }

        echo "<pre>";
        var_dump('ok');
        echo "</pre>";
        exit;
    }


    //递归查询全部伞下用户
    public function getTotalReferee($userIdArr){
        $userData = RefereeModel::where("dealer_id",'in',$userIdArr)->field("user_id")->select()->toArray();
        $resArr = [];
        $chileIdsArr = [];
        if(!empty($userData)){
            $chileIdsArr = array_column($userData,"user_id");
            $resArr = $this->getTotalReferee($chileIdsArr);
        }
        return array_unique(array_merge($resArr,$chileIdsArr));
    }




}